<template>
    <view class="container">
        <!-- 顶部导航栏 -->
        <view class="header">
            <view class="back-btn" @click="goBack">
                <image src="/static/icon/导航.png" class="back-icon" />
            </view>
            <text class="title">余额充值</text>
            <view class="right-placeholder"></view>
        </view>

        <!-- 通用信息栏 -->
        <view class="store-info">
            <text class="store-text">通用</text>
            <view class="switch-store" @click="switchStore">
                <text class="switch-text">切换门店</text>
                <text class="switch-arrow">›</text>
            </view>
        </view>

        <!-- 余额卡片 -->
        <view class="balance-card">
            <text class="balance-label">我的余额</text>
            <view class="balance-amount">
                <text class="currency">¥</text>
                <text class="amount">{{ userBalance }}</text>
            </view>
            <view class="record-btn" @click="viewRecords">
                <text class="record-text">充值记录</text>
                <text class="record-arrow">›</text>
            </view>
        </view>

        <!-- 充值金额输入 -->
        <view class="recharge-section">
            <text class="recharge-label">充值金额(元)</text>
            <view class="amount-input">
                <text class="currency-symbol">¥</text>
                <input type="digit" v-model="rechargeAmount" placeholder="请输入充值金额" class="amount-field" />
            </view>
        </view>

        <!-- 快速选择金额 -->
        <view class="quick-amounts">
            <view class="amount-item" :class="{ active: rechargeAmount === '100' }" @click="selectAmount('100')">
                <text>¥100</text>
            </view>
            <view class="amount-item" :class="{ active: rechargeAmount === '200' }" @click="selectAmount('200')">
                <text>¥200</text>
            </view>
            <view class="amount-item" :class="{ active: rechargeAmount === '500' }" @click="selectAmount('500')">
                <text>¥500</text>
            </view>
            <view class="amount-item" :class="{ active: rechargeAmount === '1000' }" @click="selectAmount('1000')">
                <text>¥1000</text>
            </view>
        </view>

        <!-- 支付按钮 -->
        <button class="pay-btn" @click="goToPay" :disabled="!isValidAmount">
            去支付
        </button>
    </view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { getApiBaseUrl } from '../../utils/config.js';

// uni类型声明
declare const uni: any;

// 用户余额
const userBalance = ref('0.00');
const rechargeAmount = ref('');

// 验证金额是否有效
const isValidAmount = computed(() => {
    const amount = Number(rechargeAmount.value);
    return !isNaN(amount) && amount > 0 && amount <= 100000;
});

// 获取用户余额
const getUserBalance = async () => {
    try {
        const token = uni.getStorageSync('token');
        if (!token) {
            uni.navigateTo({ url: '/pages/login/login' });
            return;
        }

        const apiBaseUrl = getApiBaseUrl();
        const response = await uni.request({
            url: `${apiBaseUrl}/api/mobile/user/balance`,
            method: 'GET',
            header: {
                Authorization: `Bearer ${token}`
            }
        });

        // 兼容不同平台的响应格式
        const result = response.data || (response[1] && response[1].data);
        
        if (result && result.code === 200) {
        const balance = parseFloat(result.data.balance);
        if (!isNaN(balance)) {
            userBalance.value = balance.toFixed(2);
        } else {
            console.error('获取的余额不是有效的数字:', result.data.balance);
            userBalance.value = '0.00';
        }
        } else {
            console.error('获取余额失败:', result);
        }
        console.log("余额", userBalance.value);
    } catch (error) {
        console.error('获取余额异常:', error);
    }
};

// 快速选择金额
const selectAmount = (amount: string) => {
    rechargeAmount.value = amount;
};

// 返回上一页
const goBack = () => {
    uni.navigateBack();
};

// 切换门店
const switchStore = () => {
    uni.showToast({
        title: '当前只有一家门店',
        icon: 'none'
    });
};

// 查看充值记录
const viewRecords = () => {
    uni.navigateTo({
        url: '/pages/balance/balance'
    });
};

// 去支付
const goToPay = async () => {
    if (!isValidAmount.value) {
        uni.showToast({
            title: '请输入有效的充值金额',
            icon: 'none'
        });
        return;
    }

    try {
        const amount = Number(rechargeAmount.value);
        
        // 创建充值订单
        const token = uni.getStorageSync('token');
        if (!token) {
            uni.navigateTo({ url: '/pages/login/login' });
            return;
        }

        const apiBaseUrl = getApiBaseUrl();
        
        // 显示加载提示
        uni.showLoading({
            title: '正在创建订单...'
        });
        
        const response = await uni.request({
            url: `${apiBaseUrl}/api/mobile/pay/wechat/create`,
            method: 'POST',
            data: {
                business_id: 'recharge',
                businessType: 'recharge',
                amount: amount,
                description: `余额充值 ¥${amount}`
            },
            header: {
                'Content-Type': 'application/json',
				'authorization': 'Bearer ' + token
            }
        });
        
        // 隐藏加载提示
        uni.hideLoading();
        
        // 兼容不同平台的响应格式
        const result = response.data || (response[1] && response[1].data);
        
        if (result && result.code === 200) {
            // 跳转到支付页面
            uni.navigateTo({
                url: `/pages/payment/payment?type=recharge&id=${result.data.order_id}&amount=${amount}`
            });
        } else {
            uni.showToast({
                title: result?.message || '创建充值订单失败',
                icon: 'none'
            });
        }
    } catch (error) {
        uni.hideLoading();
        console.error('充值失败:', error);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    }
};

// 页面加载时获取用户余额
onMounted(() => {
    getUserBalance();
});
</script>

<style>
page {
    background-color: #f5f5f5;
    min-height: 100%;
}

.container {
    display: flex;
    flex-direction: column;
    min-height: 100%;
}

.header {
    height: 180rpx;
    background-color: #7FB992;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 80rpx 30rpx 0;
}

.back-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
}

.back-icon {
    width: 40rpx;
    height: 40rpx;
    transform: rotate(180deg);
}

.title {
    color: #FFFFFF;
    font-size: 36rpx;
    font-weight: 500;
}

.right-placeholder {
    width: 60rpx;
}

.store-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background-color: #FFFFFF;
}

.store-text {
    font-size: 32rpx;
    color: #333;
}

.switch-store {
    display: flex;
    align-items: center;
}

.switch-text {
    font-size: 28rpx;
    color: #0066CC;
}

.switch-arrow {
    font-size: 28rpx;
    color: #0066CC;
    margin-left: 6rpx;
}

.balance-card {
    margin: 30rpx;
    background-color: #7FB992;
    border-radius: 16rpx;
    padding: 40rpx 30rpx;
    position: relative;
}

.balance-label {
    font-size: 28rpx;
    color: #FFFFFF;
    opacity: 0.9;
}

.balance-amount {
    margin-top: 20rpx;
    display: flex;
    align-items: baseline;
}

.currency {
    font-size: 36rpx;
    color: #FFFFFF;
    margin-right: 8rpx;
}

.amount {
    font-size: 72rpx;
    color: #FFFFFF;
    font-weight: 500;
}

.record-btn {
    position: absolute;
    top: 40rpx;
    right: 30rpx;
    display: flex;
    align-items: center;
}

.record-text {
    font-size: 24rpx;
    color: #FFFFFF;
    opacity: 0.9;
}

.record-arrow {
    font-size: 24rpx;
    color: #FFFFFF;
    margin-left: 6rpx;
    opacity: 0.9;
}

.recharge-section {
    margin: 30rpx 30rpx 20rpx;
    background-color: #FFFFFF;
    border-radius: 16rpx;
    padding: 30rpx;
}

.recharge-label {
    font-size: 28rpx;
    color: #999;
    margin-bottom: 30rpx;
    display: block;
}

.amount-input {
    display: flex;
    align-items: center;
}

.currency-symbol {
    font-size: 48rpx;
    color: #333;
    margin-right: 20rpx;
}

.amount-field {
    flex: 1;
    font-size: 40rpx;
    height: 80rpx;
}

/* 快速选择金额 */
.quick-amounts {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 20rpx;
    margin: 0 10rpx 40rpx;
}

.amount-item {
    width: 22%;
    height: 80rpx;
    background: #FFFFFF;
    border-radius: 10rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
    border: 1px solid #E6E6E6;
}

.amount-item.active {
    border-color: #7FB992;
    background-color: rgba(127, 185, 146, 0.1);
}

.amount-item text {
    color: #333;
    font-size: 30rpx;
}

.pay-btn {
    margin: 60rpx 30rpx 30rpx;
    background-color: #7FB992;
    color: #FFFFFF;
    height: 90rpx;
    line-height: 90rpx;
    font-size: 32rpx;
    border-radius: 45rpx;
}

.pay-btn[disabled] {
    background-color: #cccccc;
    color: #FFFFFF;
}
</style>
